package priv.liaohaolong.fullstacktest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import priv.liaohaolong.fullstacktest.dao.CaptchaMapper;
import priv.liaohaolong.fullstacktest.modal.CaptchaDO;
import priv.liaohaolong.fullstacktest.service.CaptchaService;
import priv.liaohaolong.fullstacktest.util.CaptchaUtils;
import priv.liaohaolong.fullstacktest.vo.CaptchaVO;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.UUID;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    public static final int CAPTCHA_EXPIRE_TIME = 60000;

    private final CaptchaMapper captchaMapper;

    @Autowired
    public CaptchaServiceImpl(CaptchaMapper captchaMapper) {
        this.captchaMapper = captchaMapper;
    }

    @Override
    public CaptchaVO create() throws IOException {
        // 生成验证码
        String verificationCode = CaptchaUtils.generateCaptchaText();
        // 生成图片
        byte[] image = CaptchaUtils.generateCaptchaImage(verificationCode);
        // 生成验证码 ID
        String captchaId = UUID.randomUUID().toString();
        // 保存验证码 ID 与验证码的关联记录
        captchaMapper.insert(new CaptchaDO(captchaId, verificationCode, new Timestamp(System.currentTimeMillis() + CAPTCHA_EXPIRE_TIME)));
        // 返回验证码 ID 和图片
        return new CaptchaVO(captchaId, image);
    }

    @Override
    public boolean verify(String captchaId, String captchaText) {
        return captchaMapper.exists(new QueryWrapper<CaptchaDO>()
                .eq("id", captchaId)
                .eq("text", captchaText)
                .ge("expire_time", new Timestamp(System.currentTimeMillis()))
        );
    }

    @Override
    public void clearExpired() {
        captchaMapper.delete(new QueryWrapper<CaptchaDO>()
                .lt("expire_time", new Timestamp(System.currentTimeMillis()))
        );
    }
}
